package cn.w.outdoor.lib.media;

import android.media.AudioTrack;
import android.util.Log;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.w.outdoor.lib.model.Trans_Package;
import cn.w.outdoor.lib.network.UDPTools;

public class AudioPlayer {

    private final static String TAG = "AudioPlayer";
    private final AtomicBoolean isStartAudio = new AtomicBoolean(false);

    private Queue<Trans_Package> bufferQueue;
    private AudioPlayerThread audioPlayerThread;

    private int port;
    private OnDataListener dataListener;

    public AudioPlayer(int port) {
        this.port = port;
        bufferQueue = new ConcurrentLinkedQueue<>();
    }

    public void startAudioPlayer(float volmun) {
        synchronized (isStartAudio) {
            if (!isStartAudio.get()) {
                if (audioPlayerThread == null) {
                    UDPTools.getInstance().setOnAudioDataListener(new OnDataListener() {

                        @Override
                        public void onData(Trans_Package trans_package) {
                            bufferQueue.offer(trans_package);
                        }
                    });
                    audioPlayerThread = new AudioPlayerThread(volmun);
                    audioPlayerThread.start();
                    isStartAudio.set(true);
                }
            } else {
                Log.e(TAG, "音频播放部分已经启动，无法再次启动");
            }
        }
    }

    public void stopAudioPlayer() {
        synchronized (isStartAudio) {
            if (isStartAudio.get()) {
                if (audioPlayerThread != null) {
                    audioPlayerThread.stopAudioPlay();
                    try {
                        audioPlayerThread.join();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    audioPlayerThread = null;
                    bufferQueue.clear();
                    bufferQueue = null;
                    System.gc();
                    isStartAudio.set(false);
                }
            } else {
                Log.e(TAG, "音频播放部分尚未启动，无法关闭");
            }
        }
    }

    private class AudioPlayerThread extends Thread {

        private boolean stopAudioPlayer;

        private float volumn = -1;

        public AudioPlayerThread() {

        }

        public AudioPlayerThread(float volumn) {
            this.volumn = volumn;
        }

        public void stopAudioPlay() {
            stopAudioPlayer = true;
            Log.e(TAG, "stopAudioPlayer ------------停止播放线程，stopAudioPlayer= " + stopAudioPlayer);
        }

        @Override
        public void run() {
            stopAudioPlayer = false;
            int audioBuffSize = AudioTrack.getMinBufferSize(MediaConfig.PCM_AUDIO_SAMPLERATE, MediaConfig.AUDIO_OUT_CHANNEL,
                    MediaConfig.AUDIO_FORMAT) * 2;
            AudioTrack audioTrack = new AudioTrack(MediaConfig.AUDIO_STREAMTYPE, MediaConfig.PCM_AUDIO_SAMPLERATE,
                    MediaConfig.AUDIO_OUT_CHANNEL, MediaConfig.AUDIO_FORMAT, audioBuffSize, MediaConfig.AUDIO_MODE);
            audioTrack.setStereoVolume((volumn / 100) * AudioTrack.getMaxVolume(), (volumn / 100) * AudioTrack.getMaxVolume());
            audioTrack.play();
            try {

                int readBufferSizeCount = 0;

                while (!stopAudioPlayer) {
                    Trans_Package audioBuffer = bufferQueue.poll();
                    if (audioBuffer != null && audioBuffer.getLen() > 0) {

                        if (readBufferSizeCount % 100 == 0) {
                            Log.e(TAG, "写入到音频数据的长度：" + audioBuffer.getLen());
                        }
                        readBufferSizeCount++;

                        audioTrack.write(audioBuffer.generateToBytes(), 16, audioBuffer.getLen());
                        audioTrack.flush();
                    } else {
                        Thread.sleep(1L);
                    }
                }
                Log.e(TAG, "关闭音频播放部分");
                audioTrack.stop();
                audioTrack.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
